package com.isoft.controller;

import com.isoft.service.DfmeFrttService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/flight/dfme")
public class DfmeFrttController {
    private static final Logger logger = LoggerFactory.getLogger(DfmeFrttController.class);

    @Autowired
    private DfmeFrttService dfmeFrttService;

    @PostMapping(value = "/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> uploadFlightData(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("Received DFME-FRTT file upload request: {}", file.getOriginalFilename());

            // 验证文件
            validateFile(file);

            // 处理文件
            String result = dfmeFrttService.parseAndSave(file);
            return ResponseEntity.ok().body("{\"status\":\"success\",\"message\":\"" + result + "\"}");

        } catch (Exception e) {
            logger.error("DFME-FRTT file upload failed for: {}", file.getOriginalFilename(), e);
            return ResponseEntity.internalServerError()
                    .body("{\"status\":\"error\",\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("File cannot be empty");
        }

        if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
            throw new IllegalArgumentException("Only XML files are supported");
        }

        if (file.getSize() > 10 * 1024 * 1024) { // 10MB限制
            throw new IllegalArgumentException("File size exceeds maximum limit (10MB)");
        }
    }
}